#include "ExchangeAdapterConfig.h"
#include "RMMSoftMarketAdapter.h"
#define TIXML_USE_STL
#include "tinyxml.h"
#include "simsingleton.h"
#include "FixInitiator.h"
#include "DebugUtils.h"
#include "LocalCompile.h"

RMMSOFT_NS_BEGIN

std::pair<bool,RMMSoftMarketAdapter::InitParam> 
	RMMSoftMarketAdapter::InitParam::LoadConfig(const tstring& fname)
{
	InitParam param;
	TiXmlDocument doc(fname.c_str());
	bool loadOkay = doc.LoadFile();
	TiXmlNode* pNode = NULL;
	tstring str;

	std::memset(&param,0,sizeof(param));
	if (!loadOkay)
		return std::make_pair(false,param);

	pNode = doc.FirstChild("configure");
	XML_GET_STRING(pNode,"cfgpath",param.fixcfgpath);
	XML_GET_STRING(pNode,"agentid",param.agentid);

	return std::make_pair(true,param);
}

RMMSoftMarketAdapter::RMMSoftMarketAdapter()
{
	std::memset(&m_para,0,sizeof(m_para));
}

RMMSoftMarketAdapter::~RMMSoftMarketAdapter()
{
}

tstring RMMSoftMarketAdapter::GetName()
{
	return "RMMSoftMarket";
}

bool RMMSoftMarketAdapter::InitializeByXML(const tchar* cfgpath)
{
	std::pair<bool,InitParam> it = 
		InitParam::LoadConfig(cfgpath);
	if(false == it.first)
		return false;
	return Initialize((void*)(&(it.second)));
}

bool RMMSoftMarketAdapter::Initialize(void *para)
{
	m_para = *((InitParam*)para);
	RMMSoftFixInitiator &pfix = 
		simpattern::Singleton_InClass<RMMSoftFixInitiator>::Instance();
	DBG_ASSERT(false == pfix.IsStarted());

	FixInitiatorPara fixpara;
	RMMSoftFixInitiatorPara internalfixpara;
	fixpara.fixcfgpath = m_para.fixcfgpath;
	internalfixpara.type = internalfixpara.MARKET;

	if(!pfix.RMMSoftInit(internalfixpara) || 
		!pfix.Register(m_para.agentid,this) || 
		!pfix.Init(fixpara))
		return false;
	return true;
}

void RMMSoftMarketAdapter::UnInitialize()
{
	RMMSoftFixInitiator &pfix = 
		simpattern::Singleton_InClass<RMMSoftFixInitiator>::Instance();
	pfix.Uninit();
	pfix.Unregister(m_para.agentid);
	pfix.RMMSoftUninit();
}

bool RMMSoftMarketAdapter::Login(void*)
{
	RMMSoftFixInitiator &pfix = 
		simpattern::Singleton_InClass<RMMSoftFixInitiator>::Instance();
	if(0 > pfix.Start())
		return false;
	return true;
}

bool RMMSoftMarketAdapter::Logout(void*)
{
	FixInitiator &pfix = 
		simpattern::Singleton_InClass<FixInitiator>::Instance();
	pfix.Stop();
	return true;
}

bool RMMSoftMarketAdapter::SupportDoM()
{
	return false;
}

void RMMSoftMarketAdapter::Response(FIX::Message &msg)
{
	OnResponseMsg(msg);
}

void RMMSoftMarketAdapter::AgentOnNetConnected(){}

void RMMSoftMarketAdapter::AgenOnNetDisconnected(){}

void RMMSoftMarketAdapter::AgenOnLogin()
{
	std::cout<<"RMMSoft Login Success"<<std::endl;
	PriOnLogin();
}

void RMMSoftMarketAdapter::AgenOnLogout()
{
	std::cout<<"RMMSoft Logout Success"<<std::endl;
	PriOnLogout();
}

RMMSOFT_NS_END